import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:notification_listen_service_plugin/notification_listen_body.dart';
import 'package:notification_listen_service_plugin/notification_listen_service_plugin.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _notificationListenServicePlugin = NotificationListenServicePlugin();

  String isPermissionGranted = "none";

  List<NotificationListenBody> _list = [];

  @override
  void initState() {
    super.initState();

    while (true) {
      if (context.mounted) {
        _notificationListenServicePlugin.listenNotification((NotificationListenBody v) {
          print("listen: ${v.toString()}");
          setState(() {
            _list.add(v);
          });
        });
        break;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            children: [
              GestureDetector(
                onTap: () async {
                  bool v = await _notificationListenServicePlugin.isPermissionGranted();
                  setState(() {
                    isPermissionGranted = v.toString();
                  });
                },
                child: Text('isPermissionGranted on: $isPermissionGranted\n'),
              ),
              GestureDetector(
                onTap: () async {
                  bool v = await _notificationListenServicePlugin.requestPermission();
                  setState(() {
                    isPermissionGranted = v.toString();
                  });
                },
                child: Text('requestPermission on: $isPermissionGranted\n'),
              ),
              GestureDetector(
                onTap: () async {
                  await _notificationListenServicePlugin.sendNotification("念", "测试消息");
                },
                child: const Text("send message"),
              ),
              Expanded(
                child: ListView(
                  children: _list.map((e) => Text(e.title)).toList(),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
